package com.authine.cloudpivot.engine.plugin.service.impl;

import com.authine.cloudpivot.engine.YAMLConfig;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SendSMTPMsg  {

    /**
     Outgoing Mail (SMTP) Server
     requires TLS or SSL: smtp.gmail.com (use authentication)
     Use Authentication: Yes
     Port for TLS/STARTTLS: 587
     */


    public void sendEmail(String toEmail, String subject, String body,String url,YAMLConfig config) {
        log.info("TLSEmail Start");
        Properties props = new Properties();
        //SMTP Host
        props.put("mail.smtp.host", config.getMail_smtp_host());
        props.put("mail.smtp.ssl.trust", config.getMail_smtp_ssl_trust());
        //TLS Port
        props.put("mail.smtp.port", config.getMail_smtp_port());
        //enable authentication
        props.put("mail.smtp.auth", config.getMail_smtp_auth());
        //enable STARTTLS
        props.put("mail.smtp.starttls.enable", config.getMail_smtp_starttls_enable());

        //create Authenticator object to pass in Session.getInstance argument
        Authenticator auth = new Authenticator() {
            //override the getPasswordAuthentication method
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getAccount(), config.getPassword());
            }
        };
        Session session = Session.getInstance(props, auth);
        try {
            EmailUtil.sendEmail(session,config.getAccount(), toEmail, subject, body);
            log.info("TLSEmail end");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

